/*
 * @Author       : NaN 353362604@qq.com
 * @Date         : 2023-02-24 19:31:53
 * @LastEditTime : 2023-05-04 10:36:58
 * @LastEditors  : NaN 353362604@qq.com
 * @FilePath     : \AdminStration\src\Common\Forge\ForgeWindow.jsx
 * @Description  :
 */
/*
 * @Author: 飞越疯人院 353362604@qq.com
 * @Date: 2022-06-21 15:53:43
 * @LastEditors: 飞越疯人院 353362604@qq.com
 * @LastEditTime: 2022-06-30 09:13:17
 * @FilePath: \ReconfigurationAdministration\src\Pages\TieKe\InvestList\AddForge.jsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { Modal, message, Select, Input, Tree, Checkbox, Button, Spin, DatePicker } from 'antd'
import { useEffect, useRef, useState } from 'react'
import { useBoolean, useLatest, useRequest } from 'ahooks'
import { Http } from '../Api'
import { project } from '../Data'
import dayjs from 'dayjs'

const { imageUrl } = project[window.location.hostname]
const { Autodesk, THREE } = window
const { Option } = Select
const { Group } = Checkbox
const { RangePicker } = DatePicker

const ModalSelectColor = new THREE.Vector4(255 / 255, 0 / 255, 0 / 255, 1)
const GetNewArr = (a, b) => [...a, ...b].filter(item => !(a.includes(item) && b.includes(item)))

export const ForgeBox = ({ type, Off, Data }) => {
    return (
        <Modal
            className="ModalTitle"
            open={true}
            footer={null}
            maskClosable={false}
            onCancel={Off}
            destroyOnClose
            title={`计划进度`}
            centered
            width={'90vw'}
        >
            <ForgeWindow type={type} Data={Data} />
        </Modal>
    )
}

export const ForgeWindow = ({ type, Data }) => {
    const { runAsync: getFileUris } = useRequest(Http, { manual: true })
    const { runAsync: getAllBIMConstructionTree } = useRequest(Http, { manual: true })
    const { runAsync: getBIMModlesInfoExternalId } = useRequest(Http, { manual: true })
    const { runAsync: posBIMPlanDetails } = useRequest(Http, { manual: true })
    const ForgeBox = useRef(null)
    const [Viewing, setViewing] = useState()
    const [ModalList, setModalList] = useState([])
    const [TreeData, setTreeData] = useState([])
    const [Options, setOptions] = useState([])
    const [PlainOptions, setPlainOptions] = useState([])
    const [SearchData, setSearchData] = useState([])
    const [ModalActiveData, setModalActiveData] = useState([])
    const [ModalUuid, setModalUuid] = useState('')
    const [ModalTime, setModalTime] = useState('')
    const [ModalTimeState, { setTrue: ModalTimeTrue, setFalse: ModalTimeFalse }] = useBoolean(true)
    const [ModalSelectState, { setTrue: ModalSelectTrue, setFalse: ModalSelectFalse }] = useBoolean(false)
    const [ModalTreeState, { setTrue: ModalTreeTrue, setFalse: ModalTreeFalse }] = useBoolean(false)
    const [ModalListState, { setTrue: ModalListTrue, setFalse: ModalListFalse }] = useBoolean(false)
    const [ModalListLoading, { setTrue: ModalListLoadingTrue, setFalse: ModalListLoadingFalse }] = useBoolean(false)
    const [ModalSearchState, { setTrue: ModalSearchStateTrue, setFalse: ModalSearchStateFalse }] = useBoolean(false)
    // const [ModalTreeAllState, { toggle: ModalTreeAllToggle }] = useBoolean(false)
    const [ModalTreeAllState, setModalTreeAllState] = useState([])
    const [CheckSelect, setCheckSelect] = useState([])
    const [CheckAll, setCheckAll] = useState(false)
    const [CheckAllIn, setCheckAllIn] = useState(false)
    const ModalListStateLatest = useLatest(ModalListState)
    const CheckSelectLatest = useLatest(CheckSelect)
    useEffect(() => {
        const viewing = new Autodesk.Viewing.GuiViewer3D(ForgeBox.current)
        Autodesk.Viewing.Initializer({ env: 'Local' }, () => {
            setViewing(viewing)
            message.info('初始化完成')
            getFileUris({
                url: 'getBimFileOrganizationRelation',
                data: { pageIndex: 1, pageSize: 10000 },
            }).then(({ list }) => {
                console.log(list)
                setModalList(list)
            })
        })
    }, [Data, getFileUris])
    // 选择模型
    const ModalSelect = e => {
        // 禁用模型下拉窗
        ModalSelectTrue()
        setModalUuid(e)
        // 渲染模型
        Viewing.start(imageUrl + ModalList.find(v => v.bimFilesUuid === e).url, {}, () => {
            message.success('模型加载成功!')
            Viewing.addEventListener('selection', ({ dbIdArray }) => {
                if (dbIdArray.length !== 0) {
                    if (ModalListStateLatest.current) {
                        if (CheckSelectLatest.current.findIndex(v => v === dbIdArray[0]) === -1) {
                            let list = [...CheckSelectLatest.current, ...dbIdArray]
                            onChangeCheck(list)
                        } else {
                            let list = CheckSelectLatest.current.filter(num => num !== dbIdArray[0])
                            onChangeCheck(list)
                        }
                    } else message.error('请先选择构建节点')
                }
            })
            // 判断操作状态  //判断请求接口 隔离或换色
            if (type === 'planAdd') {
                getAllBIMConstructionTree({
                    url: 'getGetBIMConstructionTree',
                    data: { filesUuid: e, BIMPlanUuid: Data.uuid },
                }).then(res => {
                    setTreeData(res)
                    ModalTreeTrue()
                })
            }
            if (type === 'planDel') {
                getBIMModlesInfoExternalId({
                    url: 'getGetBIMPlanModlesInfoExternalId',
                    data: { BIMPlanUuid: Data.uuid },
                }).then(({ list }) => {
                    setModalActiveData(list)
                    list.forEach(item => Viewing.setThemingColor(item.dbId, ModalSelectColor))
                })
                getAllBIMConstructionTree({
                    url: 'getGetBIMPlanConstructionTree',
                    data: { filesUuid: e, BIMPlanUuid: Data.uuid },
                }).then(res => {
                    setTreeData(res)
                    ModalTreeTrue()
                })
            }
            if (type === 'finishDel' || type === 'finishAdd') {
                ModalTimeFalse()
            }
        })
    }
    // 点击树节点
    const TreeSelect = (_, { node }) => {
        const { key, children } = node
        if (!children || children.length === 0) {
            ModalListTrue()
            let url = ''
            let data = { ConstructionTreeUuid: key }
            switch (type) {
                case 'planAdd':
                    url = 'getGetBIMModlesInfoExternalIdPlan'
                    data.BIMPlanUuid = Data.uuid
                    break
                case 'planDel':
                    url = 'getGetBIMPlanModlesInfoExternalId'
                    data.BIMPlanUuid = Data.uuid
                    break
                case 'finishAdd':
                    url = 'getGetBIMModlesInfoExternalIdFinish'
                    break
                case 'finishDel':
                    url = 'getGetBIMFinishModlesInfoExternalId'
                    data.BeginFinishTime = ModalTime[0]
                    data.EndFinishTime = ModalTime[1]
                    break
                default:
                    message.error('翻墙失败了吧!')
                    break
            }

            getBIMModlesInfoExternalId({ url, data })
                .then(({ list }) => {
                    let data = []
                    let plainOptions = []
                    list.forEach(item => {
                        data = [...data, { ...item, value: item.dbId, label: item.tableName }]
                        plainOptions = [...plainOptions, item.dbId]
                    })
                    Viewing.isolate(plainOptions)
                    setPlainOptions(plainOptions)
                    setOptions(data)
                })
                .catch(() => {
                    message.error('获取构建信息失败!')
                    ModalListFalse()
                })
        }
    }
    // 多选框全选
    const onChangeCheckAll = ({ target }) => {
        SelectColor(target.checked ? PlainOptions : [])
        setCheckSelect(target.checked ? PlainOptions : [])
        setCheckAll(target.checked)
        setCheckAllIn(false)
    }
    // 反选
    const ReverseSelection = () => onChangeCheck(GetNewArr(PlainOptions, CheckSelect))
    // 选择构建
    const onChangeCheck = list => {
        // console.log(CheckSelect)
        // console.log(ModalSearchState)
        // console.log(list)

        SelectColor(list)
        setCheckSelect(list)
        setCheckAllIn(!!list.length && list.length < PlainOptions.length)
        setCheckAll(list.length === PlainOptions.length)
    }
    // 保存
    const ClickSave = () => {
        ModalListLoadingTrue()
        switch (type) {
            case 'planAdd':
                let data = []
                CheckSelect.forEach(
                    item =>
                        (data = [
                            ...data,
                            {
                                modlesInfoUuid: Options.find(v => v.dbId === item).externalId,
                                organizationUuid: Data.organizationUuid,
                                bimPlanUuid: Data.uuid,
                            },
                        ]),
                )
                posBIMPlanDetails({ url: 'getBIMPlanDetails', data })
                    .then(() => {
                        message.success('计划进度添加成功!')
                        ClickCancel()
                    })
                    .catch(() => {
                        message.error('接口请求失败!')
                        ClickCancel()
                    })
                break
            case 'planDel':
                let delData = []
                CheckSelect.forEach(item => (delData = [...delData, Options.find(v => v.dbId === item).uuid]))
                posBIMPlanDetails({ url: 'posRemoveBIMPlanDetails', data: delData })
                    .then(res => {
                        message.success('计划进度删除成功!')
                        ClickCancel()
                    })
                    .catch(() => {
                        message.error('接口请求失败!')
                        ClickCancel()
                    })
                break
            case 'finishAdd':
                let finishAdd = []
                CheckSelect.forEach(
                    item =>
                        (finishAdd = [
                            ...finishAdd,
                            {
                                modlesInfoUuid: Options.find(v => v.dbId === item).externalId,
                                organizationUuid: JSON.parse(sessionStorage.getItem('UserInfo')).userOrganizations[0]
                                    .uuid,
                                finishTime: ModalTime,
                            },
                        ]),
                )
                posBIMPlanDetails({ url: 'getBIMFinishDetails', data: finishAdd })
                    .then(() => {
                        message.success('实际进度添加成功!')
                        ClickCancel()
                    })
                    .catch(() => {
                        message.error('接口请求失败!')
                        ClickCancel()
                    })
                break
            case 'finishDel':
                let finishDel = []
                CheckSelect.forEach(item => (finishDel = [...finishDel, Options.find(v => v.dbId === item).uuid]))
                posBIMPlanDetails({ url: 'posRemoveBIMFinishDetails', data: finishDel })
                    .then(res => {
                        message.success('实际进度删除成功!')
                        ModalDateTime('', ModalTime)
                        ClickCancel()
                    })
                    .catch(() => {
                        message.error('接口请求失败!')
                        ClickCancel()
                    })

                message.success('实际进度删除成功!')
                break
            default:
                break
        }
    }
    // 取消
    const ClickCancel = () => {
        Viewing.clearThemingColors()
        Viewing.showAll()
        ModalListLoadingFalse()
        ModalListFalse(false)
        setCheckAll(false)
        setCheckSelect([])
        setOptions([])
        setPlainOptions([])
        if (ModalActiveData && ModalActiveData.length !== 0)
            ModalActiveData.forEach(item => Viewing.setThemingColor(item.dbId, ModalSelectColor))
    }
    // 设置颜色
    const SelectColor = list => {
        Viewing.clearThemingColors()
        list.forEach(item => Viewing.setThemingColor(item, ModalSelectColor))
    }

    // 实际模型时间搜索 -- 查看
    const ModalDateTime = (_, e) => {
        ModalListFalse()
        setModalTime(e)
        getBIMModlesInfoExternalId({
            url: 'getGetBIMFinishModlesInfoExternalId',
            data: {
                BeginFinishTime: e[0],
                EndFinishTime: e[1],
            },
        }).then(({ list }) => {
            setModalActiveData(list)
            Viewing.clearThemingColors()
            Viewing.showAll()
            list.forEach(item => Viewing.setThemingColor(item.dbId, ModalSelectColor))
        })

        getAllBIMConstructionTree({
            url: 'getGetBIMFinishConstructionTreeByFilesUuid',
            data: {
                filesUuid: ModalUuid,
                BeginFinishTime: e[0],
                EndFinishTime: e[1],
            },
        }).then(res => {
            setTreeData(res)
            ModalTreeTrue()
        })
    }

    const ModalDateTimeAdd = (_, e) => {
        setModalTime(e)
        getAllBIMConstructionTree({ url: 'getGetBIMConstructionTreeByFilesUuid', data: { filesUuid: ModalUuid } }).then(
            res => {
                setTreeData(res)
                ModalTreeTrue()
            },
        )
    }

    return (
        <>
            <div className="ForgePlanBox" style={{ padding: 0 }}>
                <div className="ForgePlan" ref={ForgeBox}>
                    <div className="select">
                        <div className="modal">
                            <Select
                                style={{ width: '100%' }}
                                placeholder="请选择模型!"
                                onChange={ModalSelect}
                                disabled={ModalSelectState}
                            >
                                {ModalList.map((item, index) => (
                                    <Option key={`ModalList${index}`} value={item.bimFilesUuid}>
                                        {item.bim_FilesName}
                                    </Option>
                                ))}
                            </Select>
                            {/* <Button icon={<RedoOutlined />} onClick={ModalReselection} /> */}
                        </div>

                        {type === 'finishDel' && (
                            <div>
                                <RangePicker
                                    disabled={ModalTimeState}
                                    onChange={ModalDateTime}
                                    disabledDate={e => e && e > dayjs().endOf('day')}
                                />
                            </div>
                        )}
                        {type === 'finishAdd' && (
                            <div>
                                <DatePicker
                                    style={{ width: '100%' }}
                                    disabled={ModalTimeState}
                                    disabledDate={e => e && e > dayjs().endOf('day')}
                                    onChange={ModalDateTimeAdd}
                                />
                            </div>
                        )}

                        {ModalTreeState && (
                            <>
                                <div
                                    className="list"
                                    style={{
                                        height: `calc(100% - ${
                                            type === 'finishAdd' || type === 'finishDel' ? '110px' : '75px'
                                        } )`,
                                    }}
                                >
                                    <div className="tree">
                                        <Spin spinning={ModalListState}>
                                            <Tree
                                                fieldNames={{ title: 'tableName', key: 'uuid' }}
                                                onSelect={TreeSelect}
                                                treeData={TreeData}
                                            />
                                        </Spin>
                                    </div>
                                </div>
                                {/* <div className="open" onClick={TreeOpenOrOff}>{ModalTreeAllState ? '全部收起' : '全部展开'}</div> */}
                            </>
                        )}
                    </div>
                    {ModalListState && (
                        <div className="list">
                            <div className="search">
                                {/* <Search placeholder='请输入搜索的构建信息!' onSearch={SearchListData} />
                                <Button icon={<RedoOutlined />} onClick={ModalSearchStateFalse} /> */}
                            </div>
                            <div className="check">
                                <Spin spinning={ModalListLoading}>
                                    <div className="all">
                                        <Checkbox
                                            disabled={ModalSearchState}
                                            indeterminate={CheckAllIn}
                                            checked={CheckAll}
                                            onChange={onChangeCheckAll}
                                        >
                                            全选
                                        </Checkbox>
                                        <Button disabled={ModalSearchState} type="link" onClick={ReverseSelection}>
                                            反选
                                        </Button>
                                    </div>
                                    <div className="item">
                                        <Group
                                            options={ModalSearchState ? SearchData : Options}
                                            value={CheckSelect}
                                            onChange={onChangeCheck}
                                        />
                                    </div>
                                    <div className="btn">
                                        <div className="submit" onClick={ClickSave}>
                                            {type.indexOf('Add') !== -1 ? '保存' : '删除'}
                                        </div>
                                        <div className="cancel" onClick={ClickCancel}>
                                            取消
                                        </div>
                                    </div>
                                </Spin>
                            </div>
                        </div>
                    )}
                </div>
            </div>
        </>
    )
}
